/**
 * 队列
 * 特点：先进先出 FIFO （类似，排队）
 * 
 * enqueue(element(s))：向队尾添加一个或多个新的项
 * dequeue：移除队列的第一项，并返回该项
 * peek：返回队列中第一个元素
 * isEmpty：判断是否为空
 * size：返回栈里元素的长度
 * clear：清空栈里的元素
 * toString：数组中的toString方法
 *
 * @class Queue
 */
class Queue{
  constructor(){
    this._count = 0;
    this._lowestCount = 0;
    this._items = {};
  }

  isEmpty(){
    return this._count - this._lowestCount === 0;
  }

  enqueue(...elem){
    for(let i = 0; i < elem.length; i++){
      this._items[this._count] = elem[i];
      this._count ++;
    }
  }

  dequeue(){
    if(this.isEmpty()){
      return undefined;
    }

    const result = this._items[this._lowestCount];
    delete this._items[this._lowestCount];
    this._lowestCount ++;
    return result;
  }

  peek(){
    if(this.isEmpty()){
      return undefined;
    }

    return this._items[this._lowestCount];
  }

  size(){
    return this._count - this._lowestCount;
  }

  clear(){
    this._items = {};
    this._count = 0;
    this._lowestCount = 0;
  }

  toString(){
    if(this.isEmpty()){
      return '';
    }

    let objString = `${this._items[this._lowestCount]}`;
    for(let i = this._lowestCount + 1; i < this._count; i++ )
      objString = `${objString},${this._items[i]}`;
    
    return objString;
  }
}

// 测试
const queue = new Queue();
console.log(queue.isEmpty()); // true

queue.enqueue('Joho');
queue.enqueue('Jack');
console.log(queue.toString()); // Joho,Jack

queue.enqueue('Camila');
console.log(queue.size()); // 3
console.log(queue.toString()); // Joho,Jack,Camila
console.log(queue.isEmpty()); // false

queue.dequeue();
queue.dequeue();
console.log(queue.toString()); // Camila

queue.enqueue('Joho','Joho','Camila');
console.log(queue.toString());
console.log(queue);


// 击鼓传花
const hotPotato = (elementList, num) => {
  const queue = new Queue();
  const elimitatedList = [];

  for(let i = 0; i < elementList.length; i++){
    queue.enqueue(elementList[i]);
  }

  while(queue.size() > 1){
    for(let i = 0; i < num; i++){
      queue.enqueue(queue.dequeue());
    }
    elimitatedList.push(queue.dequeue());
  }

  return {
    elimitated: elimitatedList,
    winner: queue.dequeue()
  }
}

const names = ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'];
const result = hotPotato(names, 6);
result.elimitated.forEach(name => {
  console.log(`${name} 在击鼓传花中被淘汰啦`)
})

console.log(`胜利者：${result.winner}`)